package com.innovation.chengzhangriji.ui.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

public class CircleImageView extends ImageView {

    private float mRotate;

    private Animation mAnimation;

    private Animation.AnimationListener mListener;

    public float getRotate() {
        return mRotate;
    }

    public void setRotate(float rotate) {
        this.mRotate = rotate;
        invalidate();
    }

    public CircleImageView(Context context) {
        this(context, null);
    }

    public CircleImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        mAnimation.setInterpolator(new LinearInterpolator());
        mAnimation.setRepeatCount(Animation.INFINITE);
        mAnimation.setRepeatMode(Animation.RESTART);
        mAnimation.setDuration(500);
    }

    public void startRotateAnimation() {
        startAnimation(mAnimation);
    }

    public void stopRotateAnimation() {
        clearAnimation();
        mAnimation.cancel();
        mAnimation.reset();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int saveCount = canvas.getSaveCount();
        canvas.save();
        final Rect rect = canvas.getClipBounds();
        canvas.rotate(mRotate, rect.centerX(), rect.centerY());
        super.onDraw(canvas);
        canvas.restoreToCount(saveCount);
    }

    public void setAnimationListener(Animation.AnimationListener listener) {
        mListener = listener;
    }

    @Override
    public void onAnimationStart() {
        super.onAnimationStart();
        if (mListener != null) {
            mListener.onAnimationStart(getAnimation());
        }
    }

    @Override
    public void onAnimationEnd() {
        super.onAnimationEnd();
        if (mListener != null) {
            mListener.onAnimationEnd(getAnimation());
        }
    }
}
